package vn.vfriends.vcms.site.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author tuan@vfriends.vn
 */
public class GoogleAnalyticsUtils {
    
    private static final String GA_ACCOUNT = "MO-38822761-1";
    private static final String GA_PIXEL = "ga.jsp";

    public static String googleAnalyticsGetImageUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        StringBuilder url = new StringBuilder();
        url.append(GA_PIXEL + "?");
        url.append("utmac=").append(GA_ACCOUNT);
        url.append("&utmn=").append(Integer.toString((int) (Math.random() * 0x7fffffff)));

        String referer = request.getHeader("referer");
        String query = request.getQueryString();
        String path = request.getRequestURI();

        if (referer == null || "".equals(referer)) {
            referer = "-";
        }
        url.append("&utmr=").append(URLEncoder.encode(referer, "UTF-8"));

        if (path != null) {
            if (query != null) {
                path += "?" + query;
            }
            url.append("&utmp=").append(URLEncoder.encode(path, "UTF-8"));
        }

        url.append("&guid=ON");

        return url.toString();
    }
}
